package com.junsi.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLConnection;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.FileCopyUtils;

import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.MimeUtility;

import nl.bitwalker.useragentutils.UserAgent;

public class DownFile {
	
	public static final String PATH = "C:/files/";
	
	public static void download(String supplementalsFile, HttpServletResponse response,HttpServletRequest request) throws IOException {
		File file=new File(supplementalsFile);
		if(!file.exists()){
			return;
		}
		String mimeType=URLConnection.guessContentTypeFromName(file.getName());
		if(mimeType==null){
			mimeType="application/octet-stream";
		}
		response.setContentType(mimeType);
		response.setContentLength((int)file.length());
		String fileName=file.getName();
		String encodedFileName=null;
		String userAgentString=request.getHeader("User-Agent");
		String browser = UserAgent.parseUserAgentString(userAgentString).getBrowser().getGroup().getName();
		if(browser.equals("Chrome") || browser.equals("Internet Exploer") || browser.equals("Safari")) {
			encodedFileName = URLEncoder.encode(fileName,"utf-8").replaceAll("\\+", "%20");
		}else{
			encodedFileName = MimeUtility.encodeWord(fileName);
		}
		response.setHeader("Content-Disposition", "attachment;fileName=\"" + encodedFileName + "\"");
		//文件下载
		InputStream in = new BufferedInputStream(new FileInputStream(file));
		FileCopyUtils.copy(in, response.getOutputStream());
	}
}
